package com.xx.bysj.service.imp;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.xx.bysj.service.EmailService;
import com.xx.bysj.utils.NumberUtils;
import com.xx.bysj.utils.Result;
import com.xx.bysj.utils.SendEmailUtils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.util.concurrent.TimeUnit;

import static com.xx.bysj.utils.RedisConstants.LOGIN_CODE_TTL;
import static com.xx.bysj.utils.RedisConstants.REGISTER_CODE_KEY;

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class EmailServiceImpl implements EmailService {

    @Resource
    private SendEmailUtils sendEmailUtils;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendEmail(String email) {
        String emailCode = RandomUtil.randomNumbers(6);
        log.info("本次验证码为：{}",emailCode);
        String context = "<b>尊敬的用户：</b><br><br><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;您好，" +
                "校园代取快递系统提醒您本次的验证码是：<b>{}</b>，" +
                "有效期5分钟。<br><br><br><b>校园代取快递系统</b>";
        String html = StrUtil.format(context, emailCode);
        //发送邮件
        try {
            sendEmailUtils.sendHtml("【校园代取快递系统】邮箱注册验证", html, email);
        }catch (Exception e){
            log.error(e.toString());
            throw new RuntimeException("邮件发送失败");
        }
        //将验证码信息存储至redis中并设置过期时间
        stringRedisTemplate.opsForValue().set(REGISTER_CODE_KEY+email,emailCode,LOGIN_CODE_TTL, TimeUnit.MINUTES);
        return Result.success("邮件发送成功");
    }
}
